import base64
import hashlib
import random
import time


def bw_encode(val):
	"""负责编码"""
	md5_build = hashlib.md5()
	md5_build.update(val.encode())
	return md5_build.hexdigest()


def shuffle(text, count):
	while count:
		old = ''.join([v for i, v in enumerate(text) if i & 1])  # 把偶数位提前（index为奇数）
		no_old = ''.join([v for i, v in enumerate(text) if not i & 1])
		return shuffle(old + no_old, count - 1)
	return text


def un_shuffle(text, count):
	while count:
		old = text[:len(text) // 2]  # 前置向后
		no_old = text[len(text) // 2:]  # 后置向前
		text = ''.join([i[0] + i[1] for i in zip(no_old, old)])
		return un_shuffle(text, count - 1)
	return text


def my_encode(val):
	"""对数据进行加密混淆"""
	random_no = random.randint(2, 5)
	val = str((time.time() - random.randint(1, 100000))) + "_" + str(val) + "_" + str(time.time())
	step_1 = shuffle(base64.b64encode(val.encode()).decode(), random_no).replace('=', '_')
	step_2 = ''.join([str(ord(i)).zfill(3) for i in step_1])
	result = shuffle(step_2, random_no)
	return result + f"_{random_no}"


def my_decode(val):
	"""对数据进行解密"""
	random_no = int(val.split('_')[1])
	val = val.split('_')[0]
	if len(val) % 3:
		return False
	no = int(len(val) / 3)
	step1 = un_shuffle(val, random_no)
	step2 = ''.join([chr(int(step1[_*3:(_+1) * 3])) for _ in range(no)])
	result = base64.b64decode(un_shuffle(step2, random_no).replace('_', "=")).decode()
	return result.rsplit('_')[1]


class ShortLink:
	"""模拟简单的短链加减密"""

	def __init__(self):
		self.__code_map = "7Habcwxy90GSTUv6BCDEFghOPQmzA8nopfRIJ1sqrlKLMNtudijk23e45VWXYZ"
		self.__offset = 10000000

	def encrypt(self, encode_int: int):
		"""加密短链"""
		noise = int(time.time() * random.randint(1000, 100000))
		num_count = self.__offset + int(encode_int) + noise
		cache = []
		while num_count:
			cache.insert(0, self.__code_map[num_count % 62])
			num_count //= 62
		result = f"{''.join(cache)}_{noise}"
		return result

	def decrypt(self, decode_str: str):
		"""解密短链"""
		try:
			num_count = 0
			noise = int(decode_str.split('_')[1])
			decode_str = decode_str.split('_')[0]
			for idx, v in  enumerate(decode_str[::-1]):
				num_count += self.__code_map.index(v) * 62 ** idx
			return num_count - self.__offset - noise
		except:
			return -1



if __name__ == "__main__":
	#print(my_encode(1))
	#print(my_decode("509008008211504208722015047091106048087120060670850380660700507806702002802607028026178092158147070091561871250981770512804807712505808705197070087010010087_3"))
	s = ShortLink()
	print(s.encrypt(35))
	print(s.decrypt("805215012000211903704180030971818813044120180256907197095000771709012141050921604401057090780283707076132121960802208097170980901708079130821212218045018971709605897087_5"))